package com.mtw.bbs.common.web.feign;


import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mtw.bbs.common.core.enums.ResultCode;
import com.mtw.bbs.common.core.exception.BusinessException;
import com.mtw.bbs.common.core.vo.Result;
import com.mtw.bbs.common.web.util.WebUtil;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.Charset;


/**
 * feign上游异常请求统一处理
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class FeignClientErrorDecoder implements ErrorDecoder {


    private final ObjectMapper objectMapper;

    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            Reader reader = response.body().asReader(Charset.defaultCharset());
            Result<?> result = objectMapper.readValue(reader, Result.class);
            // 如果上游服务响应符合全局包装约定，再次抛出即可
            return new BusinessException(result.getCode(), result.getMesg());
        } catch (JsonParseException e) {
            String msg;
            try {
                msg = WebUtil.readerToString(response.body().asReader(Charset.defaultCharset()));
            } catch (IOException ex) {
                log.error("Feign Response 读取body异常: ", e);
                return new BusinessException(ResultCode.SERVICE_EXP.getCode(),e.getMessage());
            }
            return new BusinessException(ResultCode.SERVICE_EXP.getCode(),msg);
        }catch (Exception e){
            log.error("Feign Response 转换异常: ", e);
            return new BusinessException(ResultCode.SERVICE_EXP.getCode(),e.getMessage());
        }
    }
}

